package com.sport.setting.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.sport.apis.annotation.DIAccountUserBo;
import com.sport.common.excel.ExcelImport;
import com.sport.common.word.WordExport;
import com.sport.model.application.dtos.SportMemberUpdateDto;
import com.sport.model.application.pojos.SportMemberEnroll;
import com.sport.model.application.vos.SportMemberEnrollVO;
import com.sport.model.common.dtos.ResponseResult;
import com.sport.model.common.enums.AppHttpCodeEnum;
import com.sport.model.excel.SportGradeUnitDto;
import com.sport.model.excel.SportMemberEnrollExcelTemplate;
import com.sport.model.excel.SportMemberEnrollExport;
import com.sport.model.setting.bos.SportEventsGamesBo;
import com.sport.model.setting.dtos.SportNumberShowDto;
import com.sport.model.setting.vos.CountVo;
import com.sport.model.user.bos.AccountUserBo;
import com.sport.setting.repository.SportMeetingDefineItemRepository;
import com.sport.setting.repository.SportMemberEnrollRepository;
import com.sport.setting.service.SportMeetingDefineItemService;
import com.sport.setting.service.SportMeetingEnrollService;
import com.sport.utils.common.BaseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Slf4j
@Service
public class SportMeetingEnrollServiceImpl implements SportMeetingEnrollService {
    @Autowired
    SportMeetingDefineItemRepository sportMeetingDefineItemRepository;

    @Autowired
    SportMemberEnrollRepository sportMemberEnrollRepository;
    @Override
    public List<String> getSportItemList(){
        List<String> sportItemList=new ArrayList<>();
        List<SportEventsGamesBo> eventsGames = sportMeetingDefineItemRepository.getEventsGames(AccountUserBo.getUser().getSchoolTenementId());
        for (SportEventsGamesBo eventsGame : eventsGames) {
            sportItemList.add(eventsGame.getSportName());
        }
        return sportItemList;
    }

    @Override
    public List<SportMemberEnrollExport> getSportEnrollExport(SportGradeUnitDto sportGradeUnitDto) {
        List<SportMemberEnrollExport> list=new ArrayList<>();
        //查询比赛项目和对应的id
        Map<Long ,SportEventsGamesBo> itemMap=new HashMap<>();
        for (SportEventsGamesBo eventsGame : sportMeetingDefineItemRepository.getEventsGames(AccountUserBo.getUser().getSchoolTenementId())) {
            itemMap.put(eventsGame.getId(),eventsGame);
        }
        SportNumberShowDto sportNumberShowDto = new SportNumberShowDto(sportGradeUnitDto.getSportMemberGrade(), sportGradeUnitDto.getSportMemberUnit());
        sportNumberShowDto.setAccountUserBo(AccountUserBo.getUser());
        ResponseResult responseResult = sportMemberEnrollRepository.showQuantity(sportNumberShowDto);
        CountVo data =(CountVo) responseResult.getData();
        if(sportGradeUnitDto.isMale()){
            addMember(list, itemMap, data.getMaleList());

        }
        if(sportGradeUnitDto.isFemale()){
            addMember(list,itemMap,data.getFemaleList());
        }
        return list;

    }

    /**
     * todo：项目重复，需要修改
     * @param file
     * @return
     */
    @Override
    public ResponseResult importData(MultipartFile file) {
        if(file==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        int successNum=0;
        int failNum=0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failMsg = new StringBuilder();
        //查询比赛项目和对应的id
        Map<String,Long > itemMap=new HashMap<>();
        for (SportEventsGamesBo eventsGame : sportMeetingDefineItemRepository.getEventsGames(AccountUserBo.getUser().getSchoolTenementId())) {
            itemMap.put(eventsGame.getSportName(),eventsGame.getId());
        }
        try(ExcelImport ei=new ExcelImport(file,3,0)){
            List<SportMemberEnrollExcelTemplate> dataList = ei.getDataList(SportMemberEnrollExcelTemplate.class);
            Map<String, String> titleMap = ei.getTitle(ei);
            for (SportMemberEnrollExcelTemplate sportMemberEnrollExcelTemplate : dataList) {
                try {
                    SportMemberEnroll sportMemberEnroll = new SportMemberEnroll();
                    if (titleMap.containsKey("比赛组")) {
                        sportMemberEnroll.setSportMemberGrade(titleMap.get("比赛组"));
                    }
                    if (titleMap.containsKey("比赛单位")) {
                        sportMemberEnroll.setSportMemberUnit(titleMap.get("比赛单位"));
                    }
                    sportMemberEnroll.setSportMemberName(sportMemberEnrollExcelTemplate.getSportMemberName());
                    if (sportMemberEnrollExcelTemplate.getSportMemberGender().equals("男"))
                        sportMemberEnroll.setSportMemberGender(1);
                    else sportMemberEnroll.setSportMemberGender(2);
                    sportMemberEnroll.setSchoolTenementId(AccountUserBo.getUser().getSchoolTenementId());
                    sportMemberEnroll.setSportBindingSchool(AccountUserBo.getUser().getSportId());
                    //比赛项目设置
                    StringBuilder sportMemberProject = new StringBuilder();
                    //将属性映射为map
                    Map<String, Object> properAsMap = sportMemberEnrollExcelTemplate.getProperAsMap();
                    properAsMap.forEach((key, value) -> {
                        System.out.println(value);
                        if (value != null) {
                            if (itemMap.containsKey(value)) {
                                Long id = itemMap.get(value);
                                if (key.equals("sportMemberProject1")) {
                                    sportMemberProject.append(id.toString());
                                } else
                                    sportMemberProject.append(",").append(id.toString());
                            }
                        }
                    });
                    sportMemberEnroll.setSportMemberProject(sportMemberProject.toString());
                    //验证数据是否存在
                    SportMemberEnroll exitMember = sportMemberEnrollRepository.getOne(Wrappers.<SportMemberEnroll>lambdaQuery().eq(SportMemberEnroll::getSportMemberName, sportMemberEnroll.getSportMemberName())
                            .eq(SportMemberEnroll::getSportMemberGrade, sportMemberEnroll.getSportMemberGrade())
                            .eq(SportMemberEnroll::getSportMemberUnit, sportMemberEnroll.getSportMemberUnit()));
                    if (exitMember == null) {
                        //不存在该报名人员
                        sportMemberEnrollRepository.save(sportMemberEnroll);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、学生 " + sportMemberEnrollExcelTemplate.getSportMemberName() + "报名成功");
                    } else {
                        failNum++;
                        successMsg.append("<br/>" + successNum + "、学生 " + sportMemberEnrollExcelTemplate.getSportMemberName() + "已经报名");
                    }
                }catch (Exception e){
                    failNum++;
                    failMsg.append("<br/>" + successNum + "、学生 " + sportMemberEnrollExcelTemplate.getSportMemberName() + "报名失败");
                }
            }
        } catch (Exception e) {
            failMsg.append(e.getMessage());
            log.info(e.getMessage(),e);
        }
        if(failNum > 0){
            failMsg.insert(0, "很抱歉，导入失败！共 " + failNum + " 条数据格式不正确，错误如下：");
            log.info(failMsg.toString());
            return ResponseResult.errorResult(AppHttpCodeEnum.valueOf("很抱歉，导入失败！共 " + failNum + " 条数据格式不正确"));
        }else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

    }

    @Override
    public ResponseResult getMemberInUnit(String unit, int gender) {
        if(unit==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        List<SportMemberEnroll> memberList=sportMemberEnrollRepository.getMemberList(unit,gender);
        List<SportMemberEnrollVO> sportMemberEnrollVOS = BaseUtils.copyPropertiesList(memberList, SportMemberEnrollVO.class);
        if(memberList!=null){
        for (SportMemberEnrollVO sportMemberEnrollVO : sportMemberEnrollVOS) {
            String[] split = sportMemberEnrollVO.getSportMemberProject().split(",");
            sportMemberEnrollVO.setSportProjectList(Arrays.asList(split));
        }

            return ResponseResult.okResult(sportMemberEnrollVOS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }

    @Override
    public ResponseResult updateEnrollItem(SportMemberUpdateDto sportMemberUpdateDto) {
        boolean flag = sportMemberEnrollRepository.updateEnrollItem(sportMemberUpdateDto);
        if(flag){
            return ResponseResult.okResult("更新成功");
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    /**
     * Map<Map<String,String>,List<List<SportMemberEnrollExport>>> memberListMap
     * @return
     */
    @Override
    public void exportEnrollWord(HttpServletResponse response , String fileName) {
        try {
            WordExport wordExport = new WordExport();
            Map<Map<String,String>,List<List<SportMemberEnrollExport>>> memberListMap=new HashMap<>();
            Map<String, List<String>> map = sportMemberEnrollRepository.showGradeAndUnit();
            for (Map.Entry<String, List<String>> stringListEntry : map.entrySet()) {
                for (String unit : stringListEntry.getValue()) {
                    Map<String,String> titleMap=new HashMap<>();
                    titleMap.put("比赛组",stringListEntry.getKey());
                    titleMap.put("比赛单位",unit);
                    SportGradeUnitDto sportGradeUnitDto = new SportGradeUnitDto();
                    sportGradeUnitDto.setSportMemberGrade(stringListEntry.getKey());
                    sportGradeUnitDto.setSportMemberUnit(unit);
                    //存男生列表
                    sportGradeUnitDto.setMale(true);
                    sportGradeUnitDto.setFemale(false);
                    List<SportMemberEnrollExport> sportMaleEnrollExport = getSportEnrollExport(sportGradeUnitDto);
                    List<List<SportMemberEnrollExport>> list=new ArrayList<>();
                    list.add(sportMaleEnrollExport);
                    //存女生列表
                    sportGradeUnitDto.setMale(false);
                    sportGradeUnitDto.setFemale(true);
                    List<SportMemberEnrollExport> sportFemaleEnrollExport = getSportEnrollExport(sportGradeUnitDto);
                    list.add(sportFemaleEnrollExport);
                    memberListMap.put(titleMap,list);

                    wordExport.generateByFile(memberListMap,response,fileName);

                }
            }
        } catch (IOException e) {

            throw new RuntimeException(e);
        }

    }

    @Override
    public ResponseResult getEventsGamesToTemplate() {

        return ResponseResult.okResult(sportMeetingDefineItemRepository.getEventsGamesToTemplate());
    }

    private static void addMember(List<SportMemberEnrollExport> list, Map<Long, SportEventsGamesBo> itemMap, List<SportMemberEnroll> targetList) {
        for (SportMemberEnroll sportMemberEnroll : targetList) {
            SportMemberEnrollExport sportMemberEnrollExport = new SportMemberEnrollExport();
            sportMemberEnrollExport.setSportMemberNum(sportMemberEnroll.getSportMemberNum());
            sportMemberEnrollExport.setSportMemberName(sportMemberEnroll.getSportMemberName());
            sportMemberEnrollExport.setSportMemberGender(sportMemberEnroll.getSportMemberGrade());
            String sportMemberProject = sportMemberEnroll.getSportMemberProject();
            String[] split = sportMemberProject.split(",");
            for (int i=1;i<=split.length;i++) {
                if(itemMap.containsKey(Long.valueOf(split[i-1]))){
                    SportEventsGamesBo sportEventsGamesBo = itemMap.get(Long.valueOf(split[i-1]));
                    switch (i){
                        case 1:
                            sportMemberEnrollExport.setSportMemberProject1(sportEventsGamesBo.getSportEventsName()+sportEventsGamesBo.getSportEventsSonType());
                            break;
                        case 2:
                            sportMemberEnrollExport.setSportMemberProject2(sportEventsGamesBo.getSportEventsName()+sportEventsGamesBo.getSportEventsSonType());
                            break;
                        case 3:
                            sportMemberEnrollExport.setSportMemberProject3(sportEventsGamesBo.getSportEventsName()+sportEventsGamesBo.getSportEventsSonType());
                            break;
                        case 4:
                            sportMemberEnrollExport.setSportMemberProject4(sportEventsGamesBo.getSportEventsName()+sportEventsGamesBo.getSportEventsSonType());
                            break;
                        case 5:
                            sportMemberEnrollExport.setSportMemberProject5(sportEventsGamesBo.getSportEventsName()+sportEventsGamesBo.getSportEventsSonType());
                            break;
                    }
                }
            }
            list.add(sportMemberEnrollExport);
        }
    }
}
